const app = getApp()
const { formatDate } = require('../../lib/util')
const { getPageBills, getTotal, deleteBill, exportExcel } = require('../../api/bill')

const PAGESIZE = 20

Page({
  /** 页面的初始数据 */
  data: {
    title: [
      { key: 'type', name: '收支' },
      { key: 'category', name: '类别' },
      { key: 'money', name: '金额' },
      { key: 'date', name: '日期' }
    ],
    total: [
      { money: 0, times: 0 }, // 支出
      { money: 0, times: 0 },  // 收入
      { money: 0 }  // 结余
    ],
    bills: {
      begin: formatDate('yyyy-MM') + '-01',
      end: formatDate('yyyy-MM-dd'),
      page: 0,
      size: PAGESIZE,
      hasMore: true,
      sort: {
        index: 3,
        direct: 0
      },
      data: []
    },
    option: {
      type: '',
      content: ''
    },
    searchOrFilter: '',
    filterData: [],
    totalHeight: 80
  },
  /** 生命周期函数--监听页面加载 */
  onLoad: function (options) {
    this.modal = this.selectComponent("#modal")
    this.query = wx.createSelectorQuery()
    this.setTotalHeight()
  },
  onShow() {
    this._getBills(true)
    this._getTotal()
  },
  /** 触底加载 */
  scrollToBottom () {
    this._getBills(false, this.data.bills.page + 1)
  },
  onPullDownRefresh() {
    this._getBills(true, 1, false)
    this._getTotal(false)
    setTimeout(function () {
      wx.stopPullDownRefresh()
    }, 1500)
  },
  /** 搜索关键字 */
  onTapSearch() {
    if (this.data.searchOrFilter.length > 0) {
      this.setData({
        'searchOrFilter': '',
        'option.content': ''
      })
      this._getBills(true, 1, false)
      this._getTotal(false)
      return
    }
    this.setData({
      'option.type': 'search',
      'option.content': ''
    })
  },
  /** 输入关键字 */
  onSearchInput(e) {
    this.setData({
      'option.content': e.detail.value
    })
  },
  /** 搜索关键字内容 */
  onSearch(e) {
    var type = e.currentTarget.dataset.type
    // 取消
    if (type == 'cancel') {
      this.setData({
        'option.type': '',
        'option.content': ''
      });
      return
    }
    if (this.data.option.content.length <= 0) {
      wx.showToast({
        icon: 'none',
        title: '请输入搜索关键字',
      })
      return
    }
    this.setData({
      'option.type': '',
      'searchOrFilter': 'search'
    });
    this._getTotal(false)
    this._getBills(true, 1, false)
  },
  /** 选择类别 */
  onTapFilter() {
    if (this.data.searchOrFilter.length > 0) {
      this.setData({
        'searchOrFilter': '',
        'filterData': '',
        'option.content': ''
      })
      this._getBills(true, 1, false)
      this._getTotal(false)
      return
    }
    wx.navigateTo({
      url: '../billfilter/billfilter?begin=' + this.data.bills.begin + '&end=' + this.data.bills.end + '&filterData=' + JSON.stringify(this.data.filterData),
    })
  },
  /** 导出 */
  onTapExport() {
    this.setData({
      'option.type': ''
    })
    wx.showLoading({
      title: '正在生成Excel...',
    })
    var bills = this.data.bills
    var title = this.data.title
    exportExcel({
      begin: bills.begin,
      end: bills.end,
      sort: title[bills.sort.index]['key'],
      direct: bills.sort.direct ? 'asc' : 'desc'
    }).then(res => {
      if (res.errMsg === 'error') {
        wx.showToast({
          icon: 'none',
          title: '生成Excel失败',
        })
      } else {
        wx.showLoading({
          title: '正在下载Excel...',
        })
        wx.cloud.downloadFile({
          fileID: res.fileID,
          success: res => {
            wx.showToast({
              icon: 'none',
              title: '下载完成,正在打开...',
            })
            wx.openDocument({
              filePath: res.tempFilePath,
            })
          },
          fail: err => {
            wx.showToast({
              icon: 'none',
              title: '下载失败',
            })
          }
        })
      }
    })
  },
  /** 隐藏弹出层 */
  hideOption() {
    this.setData({
      'option.type': '',
      'option.content': ''
    })
  },
  /** 长按账单 */
  onLongTap(e) {
    this.selectedIndex = e.currentTarget.dataset.index
    this.setData({
      'option.type': 'op'
    })
  },
  /** 修改 */
  onTapChange() {
    wx.setStorageSync('editBill', this.data.bills.data[this.selectedIndex])
    this.setData({
      'option.type': '',
      'option.content': ''
    })
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  /** 删除确认 */
  onDeleteConfirm() {
    var deleteBill = this.data.bills.data[this.selectedIndex]
    this.setData({
      'option.type': 'confirm',
      'option.content': `[${deleteBill.category}，${deleteBill.money}，${deleteBill.date}]`
    })
  },
  /** 删除 */
  onTapDelete() {
    var bill = this.data.bills.data[this.selectedIndex]
    deleteBill(bill._id).then(res => {
      console.log(res)
      if (res.stats.removed > 0) {
        var bills = this.data.bills
        bills.data.splice(this.selectedIndex, 1)
        this.setData({
          bills: bills,
          'option.type': '',
          'option.content': ''
        })
        this._updateCache(bill)
      }
    })
  },
  /** 排序 */
  onTapTitle(e) {
    var sort = this.data.bills.sort
    var index = e.currentTarget.dataset.index
    if (sort.index === index) {
      this.setData({
        'bills.page': 0,
        'bills.sort.direct': !sort.direct,
        'bills.hasMore': true
      })
    } else {
      this.setData({
        'bills.page': 0,
        'bills.sort.index': index,
        'bills.sort.direct': 0,
        'bills.hasMore': true
      })
    }
    this._getBills()
  },
  setTotalHeight () {
    this.query.select('.footer').boundingClientRect(rect => {
      this.setData({ totalHeight: rect.height * 2 })
    }).exec()
  },
  /** 结束时间改变 */
  onDateChange(e) {
    var type = e.detail.type
    var value = e.detail.value
    if (type === 'begin' && value > this.data.bills.end
      || type === 'end' && this.data.bills.begin > value) {
      wx.showToast({
        icon: 'none',
        title: '开始时间不能大于结束时间',
      })
      return
    }
    this.setData({
      'bills.page': 0,
      'bills.hasMore': true,
      [`bills.${type}`]: value
    })
    wx.removeStorageSync('filter')
    this._getBills(false, 1)
    this._getTotal()
  },
  /** 加载统计 */
  _getTotal(useCache=true) {
    var bills = this.data.bills
    var total = this.data.total
    if (useCache) {
      // 1.先读缓存
      var cache = wx.getStorageSync('total')
      if (cache && cache.begin === bills.begin && cache.end === bills.end) {
        // 如果金额没改变，则return
        if (cache.data[0]['money'] === total[0]['money']
          && cache.data[1]['money'] === total[1]['money']) {
          return
        }
        this.setData({
          total: cache.data
        })
        setTimeout(()=>{this.setTotalHeight()}, 100)
        return console.log('total:缓存')
      }
    }
    // 2.查数据库
    getTotal({
      begin: bills.begin,
      end: bills.end,
      searchKey: this.data.option.content,
      filter: this.data.option.type === 'filter' ? this.data.filterData : []
    }).then(res => {
      console.log('total:数据库')
      var list = res.list
      console.log(list)
      var total = {
        begin: bills.begin,
        end: bills.end,
        data: [
          { money: 0, count: 0 },
          { money: 0, count: 0 },
          { money: 0 }
        ]
      }
      // 收支数据
      for (var i = 0, len = list.length; i < len; i++) {
        total['data'][list[i]['_id']] = {
          money: +list[i]['money'].toFixed(2),
          times: list[i]['count'] || 0
        }
      }
      // 计算余额
      total['data'][2] = {
        'money': +(total['data'][1]['money'] - total['data'][0]['money']).toFixed(2)
      }
      this.setData({
        total: total.data
      })
      setTimeout(()=>{this.setTotalHeight()}, 100)
      // 缓存
      wx.setStorageSync('total', total)
    })
  },
  /** 加载账单 */
  _getBills(init=false, page=1, useCache=true) {
    // 判断是否加载中，防止多次出发请求
    if (this.billLoading === true) return
    this.billLoading = true
    // 获取现有数据
    var bills = this.data.bills
    // 1.先读缓存，init:true表示初始化
    if (init && useCache) {
      var cache = wx.getStorageSync('bills')
      // 起止时间相同，且数据存在
      if (cache.begin === bills.begin && cache.end === bills.end 
        && cache.data && cache.data.length > 0) {
        this.setData({
          bills: cache
        })
        this.billLoading = false
        console.log('bills:缓存')
        return
      }
    }
    // 2.hasMore:true，则查询数据库
    if (init || bills.hasMore) {
      wx.showLoading()
      getPageBills({
        page: page,
        size: bills.size,
        begin: bills.begin,
        end: bills.end,
        sort: this.data.title[bills.sort.index]['key'],
        direct: bills.sort.direct ? 'asc' : 'desc',
        searchKey: this.data.option.content,
        filter: this.data.option.type === 'filter' || this.data.filterData ? this.data.filterData : []
      })
      .then(res => {
        wx.hideLoading()
        var data = res.data
        // 若为第一页，则先清空数据
        if (page === 1) {
          bills.data = []
        }
        this.setData({
          'bills.page': page,
          'bills.hasMore': data.length === PAGESIZE,
          'bills.data': bills.data.concat(data)
        })

        // 如果是第一页，且按日期降序，则缓存
        if (page === 1 && bills.sort.index === 3 && bills.sort.direct === 0) {
          bills.page = 1
          bills.hasMore = data.length === PAGESIZE
          bills.data = data
          wx.setStorageSync('bills', bills)
        }
        this.billLoading = false
        console.log('bills:数据库')
      })
    } else {
      this.billLoading = false
    }
  },
  /** 删除后更新缓存 */
  _updateCache(bill) {
    var bills = wx.getStorageSync('bills')
    var total = wx.getStorageSync('total')
    var index = bills.data.findIndex(item => {
      return bill._id === item._id
    })
    bills.data.splice(index, 1)
    total.data[bill.type]['money'] = +(total.data[bill.type]['money'] - bill.money).toFixed(2)
    total.data[bill.type]['times'] = +(total.data[bill.type]['times'] - 1).toFixed(2)
    total.data[2]['money'] = +(total.data[1]['money'] - total.data[0]['money']).toFixed(2)
    wx.setStorageSync('bills', bills)
    wx.setStorageSync('total', total)
    wx.removeStorageSync('stat_pie')
    wx.removeStorageSync('stat_com')
    wx.removeStorageSync('filter')
  },
})